package spring.chatroom.java_chatroom.server.imp;

import com.fasterxml.jackson.databind.ser.Serializers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import spring.chatroom.java_chatroom.common.constant.Constants;
import spring.chatroom.java_chatroom.common.utils.Base64Util;
import spring.chatroom.java_chatroom.mapper.UserMapper;
import spring.chatroom.java_chatroom.controller.pojo.SettingUserInfo;
import spring.chatroom.java_chatroom.server.SettingServer;

import java.io.IOException;
import java.util.Arrays;

@Slf4j
@Service
public class SettingImp implements SettingServer {

    @Autowired
    Constants constants;
    @Autowired
    UserMapper userMapper;

    @Override
    public void saveModify(SettingUserInfo userInfo) {
        try {

            if (userInfo.getHeadPortrait() != null) {
                String portraitFile = userInfo.getHeadPortrait();

                if (!verifyPortraitFile(portraitFile)) {
                    throw new RuntimeException("头像格式错误 错误的文件格式: " + portraitFile.split(",")[0]);
                }

                String filename = null;

                filename = Base64Util.saveBase64ToFile(portraitFile, constants.localPortraitPath);

                userInfo.setHeadPortrait(filename);
            }
        } catch (IOException e) {
            log.error("保存头像除了错误 {}", e.getMessage(), e);
        }

        userMapper.modifyUserInfo(userInfo);
    }


    private boolean verifyPortraitFile(String portraitFile) {
        String[] parts = portraitFile.split(",");

        if (parts.length < 2) {
            log.error("错误的格式 {}", portraitFile);
            throw new IllegalArgumentException("无效的Base64格式 - 缺少逗号分隔符");
        }

        String[] mimeType = Base64Util.extractMimeType(portraitFile).split("/");

        System.out.println("."+mimeType[1]);

        return constants.picSet.contains("."+mimeType[1]);
    }
}
